﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication4.Models;
using System.Data;

namespace MvcApplication4.Controllers
{
    public class ForumController : Controller
    {

        private ForumsEntities2 db = new ForumsEntities2();

        //
        // GET: /Forum/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult ContainedCategories()
        {
            var categories = db.Categories.Where("it.SubCategory IS NULL");
            return View("_Category_Partial", categories.ToList());
        }

        public ActionResult ContainedOP(long id)
        {
            Thread thread = db.Threads.Single(t => t.ThreadId == id);
            var post = db.Posts.Single(p => p.PostId == thread.OP);
            return View("_OP_Partial", post);
        }

        public ActionResult ContainedPosts(long id)
        {
            Thread thread = db.Threads.Single(t => t.ThreadId == id);
            var categories = db.Posts.Where("it.Thread = " + id + "AND it.PostID != " + thread.OP).OrderBy(a => a.Time);//.Take(10);
            return View("_Post_Partial", categories.ToList());
        }

        public ActionResult ContainedPostsNext(long id)
        {
            var categories = db.Posts.Where("it.Thread = " + id).OrderBy(a => a.Time).Take(10);
            return View("_Post_Partial", categories.ToList());
        }

        public ActionResult ContainedPostsPrev(long id)
        {
            var categories = db.Posts.Where("it.Thread = " + id).OrderBy(a => a.Time).Take(10);
            return View("_Post_Partial", categories.ToList());
        } 



        public ActionResult ContainedThreads(long id)
        {
            var categories = db.Threads.Where("it.Category = " + id).OrderByDescending(a => a.Time);
            return View("_Thread_Partial", categories.ToList());
        }

        public ActionResult ContainedSubCategories(long id = 0)
        {
            var categories = db.Categories.Where("it.SubCategory = " + id);
            return View("_SubCategories_Partial", categories.ToList());
        }

        public ActionResult CategorySelected(long id = 0)
        {
            Category category = db.Categories.Single(t => t.CategoryId == id);
            ViewBag.CatID = category.CategoryId;
            if (category == null)
            {
                return HttpNotFound();
            }
            
            return View(category);
        }


        public ActionResult ThreadSelected(long id = 0)
        {
            Thread thread = db.Threads.Single(t => t.ThreadId == id);
            thread.NumViews = thread.NumViews + 1;
            db.SaveChanges();

            Post post = new Post();
            post.ThreadLink = thread;
            ViewBag.ThreadId = thread.ThreadId;
          
            if (thread == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        
        /// <summary>
        /// Creates a post and adds it to the current thread.
        /// </summary>
        /// <param name="post">Post to be added</param>
        /// <param name="ThreadId">Thread where the post goes</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ThreadSelected_Create(Post post, string ThreadId)
        {
            long tempID = Convert.ToInt64(ThreadId);
            Thread thread = db.Threads.Single(t => t.ThreadId == tempID);

            User user = db.Users.Single(t => t.UserName == User.Identity.Name);
            user.NumberOfPosts++;
            post.Creator = user.UserId;
            post.Time = DateTime.Now.ToUniversalTime();
            post.Thread = thread.ThreadId;

            if (ModelState.IsValid)
            {
                db.Posts.AddObject(post);
                db.SaveChanges();

                thread.RecentPostLink = post;
                user.NumberOfPosts++;
                db.SaveChanges();

                return RedirectToAction("ThreadSelected", new { id = thread.ThreadId });
            }

            return RedirectToAction("ThreadSelected", new { id = thread.ThreadId });
        }

        public ActionResult CreateThread(long id )
        {
            Category cat = db.Categories.Single(c => c.CategoryId == id);
            Thread thread = new Thread();
            thread.CategoryLink = cat;
            ViewBag.CategoryId = cat.CategoryId;
            if (cat == null)
                return HttpNotFound();
            return View(thread);
        }

        public ActionResult Submit_CreateThread(Thread thread, string CategoryId)
        {
            long tempID = Convert.ToInt64(CategoryId);
            Category tempCat = db.Categories.Single(c => c.CategoryId == tempID);
            User tempUser = db.Users.Single(t => t.UserName == User.Identity.Name);


            Post newPost = new Post();
            newPost.Rating = 0;
            newPost.UserLink = tempUser;
            newPost.Text = thread.OPLink.Text;
            newPost.Time = DateTime.Now.ToUniversalTime();
            thread.OPLink = null;

            Thread nThread = new Thread();
            nThread.CategoryLink = tempCat;
            nThread.UserLink = tempUser;
            nThread.Time = DateTime.Now.ToUniversalTime();
            nThread.Title = thread.Title;
            //nThread.OPLink = newPost;


            if (ModelState.IsValid)
            {
                db.Threads.AddObject(nThread);
                db.SaveChanges();

                nThread = db.Threads.Single(t => t.Title == nThread.Title);
                nThread.OPLink = db.Posts.Single(p => p.Text == newPost.Text && p.Thread == nThread.ThreadId);

                nThread.NumPosts = 1;
                nThread.NumViews = 0;
                nThread.Sticky = 0;
                nThread.Rating = 0;
                nThread.Locked = 0;

                nThread.RecentPostLink = nThread.OPLink;
                
                db.SaveChanges();
            }

            return ReturnToCategory(nThread.CategoryLink.CategoryId);
        }

        public ActionResult ReturnToCategory(long id = 0)
        {
            var category = db.Categories.Single(t => t.CategoryId == id);
            if (category == null)
            {
                return HttpNotFound();
            }
            return View("CategorySelected", category);
        }

        public ActionResult ReturnToThread(long id = 0)
        {
            var category = db.Threads.Single(t => t.ThreadId == id);
            if (category == null)
            {
                return HttpNotFound();
            }
            return View("ThreadSelected", category);
        }

        //
        // GET: /Post/Create

        public ActionResult Create(long id = 0)
        {
            Thread thr = db.Threads.Single(t => t.ThreadId == id);
            ViewBag.ThreadName = thr.Title;
            ViewBag.ThreadId = thr.ThreadId;
            ViewBag.Thread = thr;
            return View();
        }

        //
        // POST: /Post/Create

        [HttpPost]
        public ActionResult Create(Post post)
        {
            
            long threadid = (long)Session[SaveVarsController.SessionThreadIdName];

            var user = db.Users.Single(t => t.UserName == User.Identity.Name);
            post.UserLink = user;
            post.Time = DateTime.Now.ToUniversalTime();

            var thread = db.Threads.Single(t => t.ThreadId == threadid);
            post.Thread = thread.ThreadId;

            if (ModelState.IsValid)
            {
                db.Posts.AddObject(post);
                db.SaveChanges();
                return RedirectToAction("ThreadSelected", new { id = thread.ThreadId } );
            }

            return RedirectToAction("ThreadSelected", new { id = thread.ThreadId });
        }


        //
        // GET: /Post/Create
        public ActionResult CreatePartial(long id = 0)
        {
            Thread thr = db.Threads.Single(t => t.ThreadId == id);
            ViewBag.ThreadName = thr.Title;
            ViewBag.ThreadId = thr.ThreadId;
            ViewBag.Thread = thr;
            return View("_Create_Partial");
        }

        //
        // POST: /Post/Create

        [HttpPost]
        public ActionResult CreatePartial(Post post)
        {
            long threadid = (long)Session[SaveVarsController.SessionThreadIdName];
            var user = db.Users.Single(t => t.UserName == User.Identity.Name);
            post.UserLink = user;
            post.Time = DateTime.Now.ToUniversalTime();

            var thread = db.Threads.Single(t => t.ThreadId == threadid);
            post.Thread = thread.ThreadId;

            if (ModelState.IsValid)
            {
                db.Posts.AddObject(post);
                db.SaveChanges();
                return CreatePartial(thread.ThreadId); //RedirectToAction("ThreadSelected", new { id = thread.ThreadId });
            }
            return CreatePartial(thread.ThreadId);
        }

        //
        // POST: /Post/Delete/5

        public ActionResult DeletePost(long id)
        {
            Post post = db.Posts.Single(p => p.PostId == id);
            Thread thread = db.Threads.Single(t => t.ThreadId == post.ThreadLink.ThreadId);
            db.Posts.DeleteObject(post);
            db.SaveChanges();
            return RedirectToAction("ThreadSelected", new { id = thread.ThreadId });
        }

        public ActionResult GetUserAvatarURL()
        {
            User user = db.Users.Single(u => u.UserName == User.Identity.Name);
            if (user.Avatar1 == null)
                return Content("");
            else
            {
                return Content(user.Avatar1.Url.ToString());
            }
        }
    }
}
